package com.zpark.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.dto.RegisterDto;
import com.zpark.entity.patients.Patients;
import com.zpark.service.PatientsService;
import com.zpark.utils.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/views")
@Api(tags = "患者注册认证")
public class RegisterController {

    @Autowired
    private PatientsService patientsService;

    @PostMapping("/register")
    @ApiOperation(value = "患者账号注册", notes = "使用用户名和密码注册")
    public ResultVO<Patients> register(@Validated @RequestBody RegisterDto dto) {
        // 检查用户名是否已存在
        if (patientsService.exists(new QueryWrapper<Patients>().eq("username", dto.getUsername()))) {
            return ResultVO.fail(400, "用户名已存在");
        }

        Patients patient = new Patients();
        patient.setUsername(dto.getUsername());
        patient.setPassword(BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt()));
        patient.setRole("patient");
        patient.setStatus(1); // 默认激活状态

        return patientsService.save(patient) ?
            ResultVO.success("注册成功", patient) :
            ResultVO.fail(500, "注册失败");
    }
}